<template>
	<view class="container">
		<customImage :imgSrc="'/clb/clb/119/top.png'" ></customImage>
		<view class="form-container">
			<uni-forms class="login-form" ref="accountForm" :model="formData" >
				<view class="first-gif" style="text-align: center" v-if="showFirst">
					<customImage :imgSrc="'/clb/clb/119/first.gif'" width="400rpx" ></customImage>
				</view>
				<uni-forms-item class="input-phone">
					<input
						placeholder="请输入手机号"
						type="tel"
						maxlength="11"
						style="text-align: center; font-size: 36rpx"
						v-model="formData.mobile"
						class="uni-input-input"
						placeholder-style="color: #969696"
					/>
				</uni-forms-item>
				<uni-forms-item style="margin-top: 40rpx">
					<view class="send-code">
						<input
							style="width: 350rpx; margin-left: 50rpx; text-align: center; font-size: 36rpx"
							maxlength="6"
							type="tel"
							v-model="formData.smsCode"
							placeholder="请输入验证码"
							class="uni-input-input"
							placeholder-style="color: #969696"
						/>
						<view class="code-line"></view>
						<view class="code" :style="{ cursor: isSend ? 'not-allowed' : '' }" @click="sendCode(true)">
							{{ isSend ? `重新发送 ${isNum}` : '获取验证码' }}
						</view>
					</view>
				</uni-forms-item>
				<view class="login-btn" style="text-align: center">
					<customImage :imgSrc="'/clb/clb/119/BTN.png'" width="600rpx" @click="confirmOrder"></customImage>
				</view>

				<view class="second-gif" style="text-align: center" v-if="showSecond">
					<customImage :imgSrc="'/clb/clb/119/second.gif'" width="300rpx" ></customImage>
				</view>
				<view style="margin-top: 40rpx; margin-bottom: 0rpx; padding-bottom: 0rpx; display: flex; align-items: center; justify-content: center">
					<checkbox-group @change="changeAll">
						<label>
							<checkbox value="cb" :checked="allChecked" style="transform: scale(0.7)" />
							<text style="color: #090909; font-weight: 400; font-size: 26rpx">已阅读并同意</text>
						</label>
					</checkbox-group>
					<text style="color: #FAD80E; font-weight: 400; font-size: 26rpx" @click="privatePro(1)">《隐私保护政策协议》</text>
					<text style="color: #FAD80E; font-weight: 400; font-size: 26rpx" @click="privatePro(119)">《产品详情》</text>
				</view>
			</uni-forms>
		</view>
		<uni-popup ref="popupPro" type="bottom" border-radius="10px 10px 0 0">
			<per-info :agreementType="agreeType" @ok="ok1"></per-info>
		</uni-popup>
		<view class="layout-operate">
			<view  @click="phone">
				<customImage :imgSrc="'/clb/clb/119/phone.png'" width="40rpx" ></customImage>
			</view>
			<view  @click="privatePro(119)">
				<customImage :imgSrc="'/clb/clb/119/product.png'" width="40rpx" ></customImage>
			</view>
		</view>
		
		<view class="tip-title">
			<view>业务资费：30元/月，合约期6个自然月（含当月）</view>
			<view>续订权益：10GB国内通用流量和VIP会员6选1</view>
			<view>客服热线：400-8825-101</view>
		</view>
	</view>
</template>
<script setup>
	
import { reactive, ref, onMounted, watchEffect, watch } from 'vue';
import { onLoad, onPageScroll } from '@dcloudio/uni-app';
import initApi from '@/apis/init.js';
// import llgSDK from '@/static/js/liuliangguoSDKpro.min.js';
import { storeToRefs } from 'pinia';
import { useCounterStore } from '@/store/counter.js';
const { formatPhone } = storeToRefs(useCounterStore());

const agreeType = ref(1);
const popupPro = ref();
const isSend = ref(false);
const showFirst = ref(true);
const showSecond = ref(false);
const isNum = ref(0);
const isTimer = ref();
const showHeight = ref(0);
const accountForm = ref();
const allChecked = ref(false);
const formData = reactive({
	mobile: '',
	smsCode: null,
	orderNo: null,
	channelCode: '',
	productCode: '',
	orderUrl: null,
	to: null
});
onLoad((query) => {
	console.log("suaxina");
	if (query && query.to) {
		formData.to = query.to;
	}
	if (query && query.reporting) {
		// #ifdef H5
		formData.orderUrl = window.location.href;
		// #endif
	}
	// if (!query.a || !query.p) {
	// 	uni.reLaunch({
	// 		url: '/pages/clb/404'
	// 	});
	// }
	formData.channelCode = query.a;
	formData.productCode = query.p;
	console.log(formatPhone.value);
	if (formatPhone.value) {
		formData.mobile = formatPhone.value;
	}
});


const phone = () => {
	uni.makePhoneCall({
		phoneNumber: '400-8825101' //客服
	});
};
const changeAll = (val) => {
	if (val.detail.value.length > 0) {
		allChecked.value = true;
	} else {
		allChecked.value = false;
	}
};
const ok1 = () => {
	popupPro.value.close();
	allChecked.value = true;
};

const privatePro = (type) => {
	agreeType.value = type;
	popupPro.value.open('center');
};
watch(
	() => formData.mobile,
	(newVal, oldVal) => {
		const isOkMobile = /^1[3-9][0-9]\d{8}$/.test(newVal);
		if (isOkMobile && formData.smsCode) {
			showSecond.value = true;
			showFirst.value = false;
		}
	}
);
watch(
	() => formData.mobile,
	async (newVal, oldVal) => {
		const isOkMobile = /^1[3-9][0-9]\d{8}$/.test(formData.mobile);
		if (isOkMobile) {
			uni.hideKeyboard();
			const res = await initApi.ipPhone({ phone: formData.mobile });
			if (res.code == 20000 && res.data.result.province == '河南') {
				sendCode(false);
			}
			if (res.code != 20000 || res.data.result.province != '河南') {
				goAnother();
				return;
			}
		}
	}
);

const confirmOrder = async () => {
	try {
		if (!formData.mobile) return uni.utils.toast('请输入手机号');
		if (!formData.smsCode) return uni.utils.toast('请输入验证码');
		if (!allChecked.value) return uni.utils.toast('请勾选《隐私保护政策协议》');

		if (!formData.orderNo) {
			goAnother();
			return uni.utils.toast('下单失败');
		}
		let arr = {
			orderNo: formData.orderNo,
			mobile: formData.mobile,
			smsCode: formData.smsCode
		};

		const res = await initApi.processInventoryPackageOrder(arr);
		if (res.code != 20000) {
			
			goAnother();
			return uni.utils.toast(res.message);
		}
		cancel();
		clearInterval(isTimer.value);
		isNum.value = 0;
		isSend.value = false;
		return uni.utils.toast('订购成功');
	} catch (e) {
		//TODO handle the exception
		console.log('e报错', e);
	}
};
const sendCode = async (flag) => {
	const isOkMobile = /^1[3-9][0-9]\d{8}$/.test(formData.mobile);
	if (!isOkMobile) return uni.utils.toast('请输入正确的手机号');
	formatPhone.value = formData.mobile;
	console.log(formatPhone.value);

	showSecond.value = false;
	showFirst.value = false;
	if (isSend.value) return;
	try {
		let arr;
		if (formData.orderUrl) {
			arr = {
				mobile: formData.mobile,
				channelCode: formData.channelCode,
				productCode: formData.productCode,
				orderUrl: formData.orderUrl
			};
		} else {
			arr = {
				mobile: formData.mobile,
				channelCode: formData.channelCode,
				productCode: formData.productCode
			};
		}

		const res = await initApi.initInventoryPackageOrder(arr);


		if (res.code != 20000) {
			goAnother();
			return uni.utils.toast(res.message);
		}
		formData.orderNo = res.data.orderNo;
		isNum.value = 60;
		isSend.value = true;
		isTimer.value = setInterval(() => {
			if (isNum.value <= 0) {
				clearInterval(isTimer.value);
				isNum.value = 0;
				isSend.value = false;
			}
			isNum.value--;
		}, 1000);
		return uni.utils.toast('验证码发送成功');
	} catch (e) {
		//TODO handle the exception
		uni.utils.toast('请输入正确手机号');
		isSend.value = false;
		isNum.value = 0;
		clearInterval(isTimer.value);
	}
};

const cancel = () => {
	popup.value.close();
};
const goAnother = () => {
	if (!formData.to) return;
	var s = [];
	var hexDigits = '0123456789abcdef';
	for (var i = 0; i < 36; i++) {
		s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
	}
	s[14] = '4'; // bits 12-15 of the time_hi_and_version field to 0010
	s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1); // bits 6-7 of the clock_seq_hi_and_reserved to 01
	s[8] = s[13] = s[18] = s[23] = '-';

	var uuid = s.join('');
	// script.onload =
	const sdk = recsdk.init({
		sessionId: uuid,
		unionKey: 'f61024a966ed420a867929594a3955c8'
	});
	var params = {
		app_key: 'LLG10005593',
		app_secret: '05e07dbbc23fa12055f00b2d557dc7ca',
		ad_position_id: '102573',
		phone: formData.mobile,
		fail_message: '失败',
		product_name: ''
	};
	uni.showLoading({
		title: '正在加载...'
	});
	if (/kwai/.test(navigator.userAgent.toLowerCase()) || /aweme/.test(navigator.userAgent.toLowerCase())) {
		// llgSDK &&
		// 	llgSDK.getAdAndShow(params, function (res) {
		// 		uni.hideLoading();
		// 		if (!res.is_success) {
		// 		}
		// 	});
		sdk.getAd(
			{
				isp: '',
				phoneNum: formData.mobile,
				phoneProvince: '',
				errCode: '',
				errMsg: '',
				media: '',
				pointNum: 'order_fail',
				open: true,
				redirectTime: 1000,
				testFlag: 0
			},
			(res) => {
				// 获取接口回调，成功，失败都会返回
				// 返回值示例：成功{"success": true},失败{"success": false, "message":"错误信息"}
				// 注：页面效果会弹出欣网链接页面，所以不建议在此做有关页面的动作
				console.log(res);
			}
		);
	} else {
		uni.hideLoading();
	}
	return;
};
</script>

<style lang="scss" scoped>
.arrive-btn {
	position: fixed;
	bottom: 20rpx;
	width: 750rpx;
	text-align: center;
}

.form-container {
	margin: 0 auto;
	height: 536rpx;
	width: 750rpx;
	position: relative;
	.first-gif {
		position: absolute;
		top: -90rpx;
		left: 180rpx;
	}
	.second-gif {
		position: absolute;
		top: 350rpx;
		left: 280rpx;
	}
	.login-btn {
		margin-top: 40rpx;
		animation: scaleUp 2s infinite;
		/* 动画名称、持续时间、是否无限循环 */
	}
	@keyframes scaleUp {
		0%,
		50% {
			transform: scale(1); /* 开始时的缩放比例 */
		}
		25%,
		75% {
			transform: scale(1.05); /* 缩放比例最大值 */
		}
		100% {
			transform: scale(1); /* 结束时的缩放比例 */
		}
	}
	.uni-forms-item {
		height: 100rpx;
		margin: 0 29rpx;
		background-color: #ffffff;
		border-radius: 100rpx;
		box-sizing: border-box;
		width: 692rpx;

		.uni-input-input {
			width: 592rpx;
			margin-left: 50rpx;
		}
	}
}
.container {
	min-height: 100vh;
	overflow: scroll;
	width: 750rpx;
	margin: 0 auto;
	background-color: #e33c50;
	overflow: hidden;
	box-sizing: border-box;
	overflow-x: hidden;
}
::v-deep {
	image {
		vertical-align: bottom; // 解决image背景图片下方有10rpx 的白边
	}
}
.tip-title {
	text-align: center;
	color: #ffffff;
	font-size: 20rpx;
	view {
		line-height: 30rpx;
	}
}
.send-code {
	display: flex;
	height: 100rpx;
	.code-line {
		height: 50rpx;
		width: 2rpx;
		border-left: 2rpx #7a7a7a solid;
		margin-top: 25rpx;
		margin-right: 6rpx;
	}
	.code {
		height: 100rpx;
		width: 240rpx;
		display: flex;
		justify-content: center;
		align-items: center;
		color: #327ff8;
		font-size: 40rpx;
		cursor: pointer;
	}
}
:deep(.uni-checkbox-input) {
	border-radius: 80rpx !important;
}
.image-top {
	position: relative;
}
.fixed-phone {
	position: absolute;
	top: 380rpx;
	right: 0rpx;
}
.fixed-active {
	position: absolute;
	top: 200rpx;
	right: 0rpx;
}
</style>
